<?php
/**
* for create selector from specify ctrl name
* the parameter sent pass url
* 
* @param ctrl the controller name
* @param filter the where condition [optional]
* @param name the HTML selector name [optional]
* @return string html selector
* @example
* <code>
*    var div_subcate = document.getElementById('subcategory_container');
*    var category = document.getElementById('form_category_id_');
*    var filter = "&filter=scy_category_id = '" + category.value + "'";
*    var name = "&name=form[subcategory_id]";
*    var url = "index.php?module=iCarrent&type=ajax&func=selector&ctrl=Sub_Category" + filter + name + genSession() ;
*    //alert(url);
*    new Ajax.Request(url, {
*        method:'get',
*        onSuccess: function(transport){
*         var result = transport.responseText;
*         div_subcate.innerHTML= result;
*         }	   
*      });
*    
*  }
* </code>
*/
function iCarrent_ajax_selector(){
  $ctrl         = FormUtil::getPassedValue ('ctrl', false , 'GET');
  $filter       = FormUtil::getPassedValue ('filter', '1 = 1' , 'GET');
  $name         = FormUtil::getPassedValue ('name', 'selector_' . $ctrl, 'GET');
  $selected     = FormUtil::getPassedValue ('selected', -1234, 'GET');
  $defaultValue = FormUtil::getPassedValue ('defaultValue', 0, 'GET');
  $defaultText  = FormUtil::getPassedValue ('defaultText', 'กรุณาเลือก', 'GET');
  $allValue     = FormUtil::getPassedValue ('allValue', 0, 'GET');
  $allText      = FormUtil::getPassedValue ('allText', '', 'GET');
  $filter  		= $filter." order by scy_name";
  if (($class = Loader::loadClassFromModule ('iCarrent', $ctrl, true)) && $ctrl){
    $objectArray = new $class();
    $objectArray->get ($filter);
    
    echo $objectArray->getSelector (strtolower($name) , $selected, $defaultValue, $defaultText,
                          $allValue, $allText);

    
  }
  return true;
}
/**
* for get ajax data for specify ctrl name
* the template name format "ajax_$func_$ctrl.htm"
*/
function iCarrent_ajax_list() {

    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');

    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'list' , 'GET');
    //pagnigation variable
    $filter  = FormUtil::getPassedValue ('filter', 0);
    $offset  = FormUtil::getPassedValue ('startnum', 0);
    $sort    = FormUtil::getPassedValue ('sort', '');


    $pagesize = FormUtil::getPassedValue ('pagesize', 100 , 'GET');
    $render = pnRender::getInstance('iCarrent');
    $render->assign ('_GET', $_GET);
    $render->assign ('_POST', $_POST);
    $render->assign ('_REQUEST', $_REQUEST);

    if ($class = Loader::loadClassFromModule ('iCarrent', 'Ajax' . ucfirst($ctrl), true)){

      $objectArray = new $class ();
      $where   = null;
      $sort = null;
      if (method_exists($objectArray,'genPermission')){
        $permit = $objectArray->genPermission();
        if (empty($permit)){
          return LogUtil::registerError ("ส่วนนี้ถูกจำกัดให้ใช้ได้เฉพาะสมาชิกเท่านั้น");
        }
      }
      if (method_exists($objectArray,'genFilter')){
        $where = $objectArray->genFilter();
      }

      if (method_exists($objectArray,'genSort')){
        $sort = $objectArray->genSort();
      }
      if (method_exists($objectArray,'selectExtendResult')){
        $resultex = $objectArray->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
      if (empty($where)){
        $where = $objectArray->_objWhere;
      }
      if (empty($sort)){
        $sort = $objectArray->_objSort;
      }
      $objectArray->get ($where, $sort , $offset, $pagesize);
      //print_r($objectArray->_objData); exit;
      //assign to view

    

      $render->assign('objectArray', $objectArray->_objData);
    }

    $render->assign('ctrl', $ctrl);
    $render->assign('setting',InnoUtil::getSetting());
    if ($lang){
      $render->assign('lang', $lang);
    }else{
      $render->assign('lang', pnUserGetLang());
    }
    echo $render->fetch('ajax_'.$func.'_'.strtolower($ctrl).'.htm');
    return true;
}

function iCarrent_ajax_view(){
    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'view' , 'GET');
    //$id the id no if edit form
    $id      = FormUtil::getPassedValue ('id', null , 'GET');
    $where   = '';

    $render = pnRender::getInstance('iCarrent');
    $render->assign ('_GET', $_GET);
    $render->assign ('_POST', $_POST);
    $render->assign ('_REQUEST', $_REQUEST);
    
    if ($id){
      //load class
      if (!($class = Loader::loadClassFromModule ('iCarrent', 'Ajax' . ucfirst($ctrl), false)))
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");

      $object  = new $class ();

      if (method_exists($object,'genPermission')){
        $permit = $object->genPermission();
        if (empty($permit)){
          return LogUtil::registerError ("ส่วนนี้ถูกจำกัดให้ใช้ได้เฉพาะสมาชิกเท่านั้น");
        }
      }

      $object->get($id);
      if (method_exists($object,'selectExtendResult')){
        $resultex = $object->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
      $render->assign ('view', $object->_objData);
    }
    $render->assign('ctrl', $ctrl);
    $render->assign('setting',InnoUtil::getSetting());
    if ($lang){
      $render->assign('lang', $lang);
    }else{
      $render->assign('lang', pnUserGetLang());
    }
    echo $render->fetch('ajax_'.$func.'_'.strtolower($ctrl).'.htm');
    return true;
}
/*
* for save setting value with none redirect
* ex module=iCarrent&type=ajax&func=save&ctrl=Setting
*    &form[id]=1&form[value]=myval
*/
function iCarrent_ajax_save(){
  $ctrl =  FormUtil::getPassedValue ('ctrl', null);
  if (!($class = Loader::loadClassFromModule ('iCarrent', $ctrl))){
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");
  }
  $object = new $class ();
  if (method_exists($object,'genPermission')){
    $permit = $object->genPermission();
    if (empty($permit)){
      return LogUtil::registerError ("ส่วนนี้ถูกจำกัดให้ใช้ได้เฉพาะสมาชิกเท่านั้น");
    }
  }
  $object->getDataFromInput ('form');
  $object->save ();
  return true;
}
/**
* for get server information
* return page title
*/
function iCarrent_ajax_getServerInfo(){
  Loader::loadFile ('JSON.php', 'includes/classes/JSON');
  $settingArray = InnoUtil::getSetting();
  $result['name'] = pnConfigGetVar('sitename');
  $result['latitude'] = $settingArray['MAP_LATITUDE'];
  $result['longitude'] = $settingArray['MAP_LONGITUDE'];
  $json = new Services_JSON();
  echo $json->encode($result);
  return true;
}

/**
* for delete object for database by specify id
*/
function iCarrent_ajax_delete() {
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');
    $id      = FormUtil::getPassedValue ('id', false , 'GET');
    $forward = FormUtil::getPassedValue ('forward', false , 'GET');

    if ($id){
      //load class
      if (!($class = Loader::loadClassFromModule ('iCarrent','User' . ucfirst($ctrl), false)))
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");

      $object  = new $class ();
      $object->_objData[$object->_objField] = $id;
      if (method_exists($object,'genPermission')){
        $permit = $object->genPermission();
        if (empty($permit)){
          return LogUtil::registerError ("ส่วนนี้ถูกจำกัดให้ใช้ได้เฉพาะสมาชิกเท่านั้น");
        }
      }
      $object->delete ();
      
    }
    return true;
}
/**
* update date to now
*/
function iCarrent_ajax_upTopics(){
  $uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
  $item_id = FormUtil::getPassedValue ('item_id', false , 'GET'); //resource id
  $setting = InnoUtil::getSetting();
  $user    = InnoUtil::getUserInfo();
  $start_date  = date("Y-m-d H:i:s");
  //$expire_date = date("Y")."-".date("m")."-".(date("d")+7);
  $expire_date  = Date("Y-m-d",mktime(0, 0, 0, date("m")  , date("d")+7, date("Y")));
  if($user['uid']==2 || $user['uid'] ==58){
    $object = array('id' => $item_id ,
                    'isuptopic'=>'1',
                    'start_uptopic'  =>$start_date ,
                    'expire_uptopic' =>$expire_date,
                    'temp_cr_date'   =>$start_date 
                    );
    DBUtil::updateObject($object,'icarrent_topics');
    echo "0:หัวข้อนี้ถูกดึงขึ้นเรียบร้อยแล้ว";
  }else if ($uid == $user['uid']){



    $sql_update_expire = "UPDATE
                            zk_icarrent_topics
                          SET
                            tpc_isuptopic = 2,
                            tpc_temp_cr_date = tpc_cr_date
                          WHERE
                            tpc_cr_uid = $uid 
                          AND
                            tpc_isuptopic = 1
                          AND
                            DATE(tpc_expire_uptopic) < DATE(NOW())";
    DBUtil::executeSQL($sql_update_expire);

    //echo $sql_update_expire;
    //Query total data
    $sql_count = "SELECT
                    COUNT(tpc_isuptopic) AS 'count_uptopic'
                  FROM
                    zk_icarrent_topics 
                  WHERE
                    tpc_cr_uid = $uid 
                  AND
                    tpc_isuptopic = 1
                  ";

    $column_count = array("count_uptopic");
    $result_count = DBUtil::executeSQL($sql_count);
    $countArray = DBUtil::marshallObjects ($result_count, $column_count);
    $count_uptopic = $countArray[0]['count_uptopic'];
    //echo $sql_count.":".$count_uptopic;

    //Query total data
    $sql_diff_date = "SELECT
                        DATEDIFF(DATE(tpc_expire_uptopic),CURDATE()) AS 'diff_date'
                      FROM
                        zk_icarrent_topics 
                      WHERE
                        tpc_cr_uid = $uid 
                      AND
                        tpc_isuptopic = 1
                      AND 
                        tpc_id = $item_id
                      ";

    //echo $sql_diff_date;
    $column_diff_date = array("diff_date");
    $result_diff_date = DBUtil::executeSQL($sql_diff_date);
    $diffDateArray = DBUtil::marshallObjects ($result_diff_date, $column_diff_date);
    $diff_date = $diffDateArray[0]['diff_date'];
    //echo $diff_date;

    if($count_uptopic == 3 && isset($diff_date)){
      echo "1:หัวข้อนี้ถูกดึงขึ้นแล้ว เหลือเวลาอีก ".$diff_date." วัน";
    } else if($count_uptopic == 3 ){
      echo "1:คุณดึงหัวข้อขึ้นครบ 3 หัวข้อแล้ว กรุณาลองใหม่อีกครั้งในที่วันครบกำหนด";
    }else {
      if($diff_date<=0 && $count_uptopic < 3){

        $object = array('id' => $item_id ,
                        'isuptopic'=>'1',
                        'start_uptopic'  =>$start_date ,
                        'expire_uptopic' =>$expire_date,
                        'temp_cr_date'   =>$start_date 
                        );
        DBUtil::updateObject($object,'icarrent_topics');
        echo "0:หัวข้อนี้ถูกดึงขึ้นเรียบร้อยแล้ว";
      } else{
        echo "1:หัวข้อนี้ถูกดึงขึ้นแล้ว เหลือเวลาอีก ".$diff_date." วัน กรุณาเลือกหัวข้ออื่น";
      }
    } 
  }
  return true;
}
/**
* delete topics
*/
function iCarrent_ajax_deleteTopics(){
  $uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
  $item_id = FormUtil::getPassedValue ('item_id', false , 'GET'); //resource id
  $setting = InnoUtil::getSetting();
  $user    = InnoUtil::getUserInfo();
  if ( $item_id && (intval($user['level'])  == intval(constant('ADMIN_EDIT_LEVEL')) || $uid == $user['uid'] )){
    if (!($class = Loader::loadClassFromModule ('iCarrent', 'UserTopics' , $is_array))){
        return LogUtil::registerError ("Unable to load class [$ctrl] ...");
    }
    $object = new $class ();
    $object->_objData = array('id' => $item_id);
    if (method_exists($object,'genPermission')){
      $permit = $object->genPermission();
      if (empty($permit)){
        return LogUtil::registerError ("ERROR: Delete operation permession denied.");
      }
    }
    $object->delete ();
  }
  return true;
}
/**
* move topics to sale and set status to sale
*/
function iCarrent_ajax_moveTopics(){
  $uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
  $item_id = FormUtil::getPassedValue ('item_id', false , 'GET'); //resource id
  $setting = InnoUtil::getSetting();
  $user    = InnoUtil::getUserInfo();
  if (  $uid == $user['uid'] ){
    //unset recommend status
    //set type to sale
    //set obj_status to sale
    $object = array('id'=>$item_id, 'type_id'=>'3','status'=>'F','obj_status' => 'S' );
    DBUtil::updateObject($object,'icarrent_topics');
  }
  return true;
}

/**
* set recommend topics
*/
function iCarrent_ajax_recTopics(){
  $uid = FormUtil::getPassedValue ('uid', false , 'GET'); //icon | image | video | model
  $item_id = FormUtil::getPassedValue ('item_id', false , 'GET'); //resource id
  $setting = InnoUtil::getSetting();
  $user    = InnoUtil::getUserInfo();
  if (  $uid == $user['uid'] ){
    //set recommend status
    $object = array('id'=>$item_id, 'status'=>'T' );
    DBUtil::updateObject($object,'icarrent_topics');
  }
  return true;
}

//create captcha image
function iCarrent_ajax_getCaptcha(){
  $result = pnModAPIFunc('iCarrent', 'ajax', 'createAjaxCaptchaImage');
  return true ;
}

/**
* for get server information
* return page title
*/
function iCarrent_ajax_sendEmail(){

  $isValidate = false;
  $captcha = trim(FormUtil::getPassedValue ('captcha', '' , 'GET')); 

  if($captcha == '77' || $captcha == '76' ) {
    $fromEmail = FormUtil::getPassedValue ('sendfrom', false , 'GET'); 
    $toEmail = FormUtil::getPassedValue ('sendto', false , 'GET');
    $message = FormUtil::getPassedValue ('message', false , 'GET');
    $forum_id = FormUtil::getPassedValue ('forum_id', false , 'GET');

    //$header mail
    $subject = '=?utf-8?B?'.base64_encode(strip_tags("รายการประกาศที่น่าสนใจ www.truck2hand.com")).'?=';
    $header  = "MIME-Version: 1.0\r\n";
    $header .= "Content-type: text/plain; charset=utf-8\r\n";
    $header .= "From: $fromEmail\r\n";
    $header .= "Reply-To: $fromEmail\r\n";
    $header .= "X-Mailer: PHP/picoHosting";

    //[Body mail]
    $body .= "\t    มีรายการประกาศที่น่าสนใจเกี่ยวกับรถบรรทุกใน www.truck2hand.com ส่งมาจากเพื่อนของคุณ\n";
    $body .= "สามารถเข้าไปดูประกาศแนะนำได้ที่  http://www.truck2hand.com/index.php?module=iCarrent&func=list&ctrl=posts&id=$forum_id\n";
    $body.= "\n";
    $body.= "[ข้อความที่ส่งมาด้วย]\n";
    $body.= fixEncoding($message)."\n";
    //$body.= "$message\n";
    $body.= "\n";
    $body.= "ขอบคุณที่ร่วมเป็นส่วนหนึ่งกับเรา\n";
    $body.= "info@truck2hand.com";
    $body.= "             ";

    mail($toEmail, $subject, $body, $header);
    $isValidate = "true";
  }else{
    $isValidate = "false";
  }

  echo $isValidate;
  pnShutdown();
}

  function iCarrent_ajax_addFavourite(){

    $topic_id = FormUtil::getPassedValue ('topic_id', false , 'GET');
    $topic_uid = FormUtil::getPassedValue ('topic_uid', false , 'GET');
    $ctrl =  FormUtil::getPassedValue ('ctrl', null);
    $uid = FormUtil::getPassedValue ('uid', false , 'GET');
    $user    = InnoUtil::getUserInfo();

    if ($uid == $user['uid'] ){
      if (!($class = Loader::loadClassFromModule ('iCarrent', $ctrl , false))){
          return LogUtil::registerError ("Unable to load class [$ctrl] ...");
      }
      $object = new $class();

      $object->_objData[topic_id] = $topic_id;
      $object->_objData[topic_uid] = $topic_uid;
      $object->_objData[uid] = $uid;
      
      $where = "WHERE fav_topic_id = '$topic_id' AND fav_topic_uid = '$topic_uid' AND fav_uid = '$uid' ";
      $checkDuplicateFavourite = DBUtil::selectObject('icarrent_favourite',  $where);

      if(empty($checkDuplicateFavourite)){
        $object->save ();
      }
    } else {
      //echo "failed.";
    }


    return true;
  }

  function fixEncoding($in_str) { 
    $cur_encoding = mb_detect_encoding($in_str) ; 
    /*
      $mb_encoding  = mb_check_encoding($in_str,"UTF-8");
      return $cur_encoding."<br>mb :".$mb_encoding;
    */
    if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8")) 
      return $in_str; 
    else 
      return utf8_encode($in_str); 

  } // fixEncoding 